(function() {
  app.controller('loginCtrl', function(toast, $rootScope, $scope, $state, tradeApi, alertTip, $window, local_m, $timeout, my_zxg_v, centerdilog, $stateParams) {
    $scope.client = { mobile: $stateParams.mobile ? $stateParams.mobile : (local_m.get('remeberaccount') || ''), };
    $scope.init = function() {
      if ($stateParams.mobile) { // 点击和讯免费体验来的用户
        centerdilog
          .open({
            ok: function() {},
            cancel_hiden: false,
            oktxt: '点击这里登录',
            tpl: '<div><img src="img/yiyuan-code.png" id="go-to-code-help"/><p style="font-weight:700">点击二维码关注我们</p></div>',
            tpl_cb: function() {
              $('#go-to-code-help').on('click', function() {
                $state.go('wx-focus');
              });
            }
          });
      }
    };

    $scope.ok = function() {
      tradeApi
        .query({
          funcId: '300001',
          data: $scope.client
        })
        .then(function(res) {
          tradeApi.sessionId = res.session;
          sessionStorage.setItem('session', res.session);
          sessionStorage.setItem('mobile', $scope.client.mobile);
          my_zxg_v
            .updata('http');

          if ($scope.checked) {
            local_m.set('remeberaccount', $scope.client.mobile);
          } else {
            local_m.set('remeberaccount', '');
          }

          alertTip
            .open({
              msg: '登录成功!',
              state: 1,
            });

          return tradeApi.query({
            funcId: '300034',
            data: {}
          });

        })
        .then(function(result) {
          if (result && result.length > 0) {
            toast.ifVip(true);
          }

          return tradeApi.query({
            funcId: '300036',
            data: {
              pay_id: '10',
            }
          });

        })
        .then(function(res) {
          if (!$stateParams.mobile) {
            $window.history.back();

            $timeout(function() {
              if (!$stateParams.go_to) return;
              $state.go($stateParams.go_to, $stateParams.go_to_params ? $stateParams.go_to_params : undefined);
            }, 200);
            return;
          }

          if ($stateParams.next) $state.go($stateParams.next);
          if (res && res[0].coupon_count !== '0') {
            $state.go('search', { type: 'free-wx' });
          } else {
            $state.go('home');
          }
        });
    };
  });

})();
